<template id="carType">
  <div>
    <el-row style="height: 100%;border: 1px solid #DCDFE6;margin-top: 10px">
      <el-col :span="6" style="border-right: 1px solid #DCDFE6; min-height:500px;">
        <div class="grid-content bg-purple">
          <el-tree :data="carTypes" :props="defaultProps" @node-click="handleNodeClick">
          </el-tree>
        </div>
      </el-col>
      <el-col :span="17" style="margin-left: 10px;padding-top: 10px">
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
          <el-form :inline="true" :model="filters">
            <el-form-item>
              <el-input v-model="filters.keyword" placeholder="关键字"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" v-on:click="getList">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleAdd">新增</el-button>
            </el-form-item>
          </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="datas" highlight-current-row @selection-change="selsChange" style="width: 100%;">
          <el-table-column type="selection">
          </el-table-column>
          <el-table-column prop="name" label="车辆名称" width="120" sortable>
          </el-table-column>
          <el-table-column prop="description" label="描述" width="120" sortable>
          </el-table-column>
          <el-table-column prop="icon" label="图标" width="120" sortable>
            <template slot-scope="scope">
              <img fit="concat" width="120" height="90" :src="scope.row.icon" alt="图片加载失败">
            </template>
          </el-table-column>
          <el-table-column prop="index" label="排序" width="120" sortable>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template scope="scope">
              <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-popconfirm
                  class="ml-5"
                  confirm-button-text='确定'
                  cancel-button-text='我再想想'
                  icon="el-icon-info"
                  icon-color="red"
                  title="您确定删除吗？"
                  @confirm="handleDel(scope.$index, scope.row)"
              >
                <el-button type="danger" size="small" slot="reference">删除<i class="el-icon-remove-outline"></i>
                </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
          <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
        </el-col>

      </el-col>
    </el-row>

    <!--新增界面-->
    <el-dialog title="新增" :visible.sync="addFormVisible" :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" ref="addForm">
        <el-form-item label="车辆名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="LOGO" prop="icon">
          <!--          <el-input v-model="addForm.icon" auto-complete="off"></el-input>-->
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/fastDfs/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              name="file"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="index">
          <el-input v-model="addForm.index" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="addForm.description" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormClose">取消</el-button>
        <el-button type="primary" @click.native="addSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.el-row {
  margin-bottom: 20px;
  height: 100%;
}

:last-child {
  margin-bottom: 0;
}

#carType el-col {
  border: 1px solid red;
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
</style>

<script>
import {h} from "vue";

export default {
  data() {
    return {
      fileList: [],
      addForm: {
        name: "",
        icon: "",
        index: "",
        description: "",
        pid: ""
      },
      addFormVisible: false,
      sels: [],
      filters: {
        keyword: ""
      },
      datas: [],
      carTypes: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    //图片预览
    handlePreview(file) {
      console.log(file);
    },
    //文件上传成功回调
    handleSuccess(response, file, fileList) {
      this.addForm.icon = response.data;
    },
    //文件删除
    handleRemove(file, fileList) {
      var filePath = file.response.data;
      this.$http.delete("/fastDfs/delete?filePath=" + filePath)
          .then(res => {
            if (res.data.success) {
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
              this.addForm.icon = ''
            } else {
              this.$message({
                message: '删除失败!',
                type: 'error'
              });
            }
          })
    },
    // 模态框关闭按钮
    addFormClose() {
      this.addFormVisible = false;
      if (this.addForm.icon != '' && this.addForm.icon != null) {
        // 关闭模态框，设置模态框的内容为空并且删除上传到服务器的图片
        this.$http.delete("/fastDfs/delete?filePath=" + this.addForm.icon)
            .then(res => {
              if (res.data.success) {
                console.log("删除成功")
              } else {
                console.log("删除失败")
              }
            })
        this.fileList = []
      }
    },
    handleAdd() {
      this.addFormVisible = true;
      this.addForm = {
        name: "",
        icon: "",
        index: "",
        description: "",
        pid: this.addForm.pid
      }
      this.fileList = []
    },
    addSubmit() {
      let {pid} = this.addForm
      if (pid == null || pid == '') {
        this.addForm.pid = 0
      }
      //提交
      this.$http.put("/carType", this.addForm).then(res => {
        //{success: true, ..
        var ajaxResult = res.data;
        if (ajaxResult.success) {
          this.addFormVisible = false;
          this.$message({
            message: '提交成功',
            type: 'success'
          });
          this.getTreeData();
        } else {
          this.$message({
            message: ajaxResult.message,
            type: 'error'
          });
        }
      });
    },
    handleCurrentChange() {

    },
    batchRemove() {
      var ids = [],icons = [];
      this.handleFilterIds(this.sels, ids, icons);
      var map = {"ids":ids,"icons":icons}
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/carType", map)
            .then(res => {
              res = res.data;
              if (res.success) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.getTreeData();
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
            })
            .catch(res => {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            });
      }).catch(() => {

      });
    },
    handleEdit() {

    },
    handleDel(index, row) {
      /*删除该分类以及该分类下的所有元素,有两种方法：
      第一种：直接将整个row传入后端，先删除row这一行，使用递归删除row.children中的元素,特点：需要执行好几次数据库操作
      第二种：使用代码先将删除的所有id递归遍历出来,然后将整个id数组传入后端使用SQL中的where in一次性删除,特点：一次性删除，效率高
          采用第二种方法
      */

      // 1.定义个数组,将自己的id先放入数组
      var ids = [],icons = [];
      ids.push(row.id);
      icons.push(row.icon);
      // 2.递归遍历row.children,将其id放入数组
      this.handleFilterIds(row.children, ids,icons);
      var map = {"ids":ids,"icons":icons}
      this.$http.patch("/carType", map)
          .then(res => {
            res = res.data
            if (res.success) {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getTreeData();
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          })
          .catch(res => {
            this.$message({
              message: '删除失败',
              type: 'error'
            });
          })
    },
    handleFilterIds(arrays, ids, icons) {
      // 1.判断当前元素是否为空,若不为空则将这个数组的id都取出来放入ids中
      if (arrays != null && arrays.length > 0) {
        for (let i = 0; i < arrays.length; i++) {
          ids.push(arrays[i].id);
          icons.push(arrays[i].icon);
          // 2.判断当前元素是否有children,若有则将其children递归遍历,将其id放入数组
          if (arrays[i].children != null && arrays[i].children.length > 0) {
            this.handleFilterIds(arrays[i].children, ids,icons);
          }
        }
      }
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    getList() {

    },
    handleNodeClick(row) {
      this.datas = row.children;
      this.addForm.pid = row.id;
    },
    getTreeData() {
      // 发送一个异步请求: get请求 /product/carType/treeData
      this.$http.get("/carType/tree").then(res => {
        res = res.data;
        this.carTypes = res.data;
        this.datas = res.data
      });
    }
  },
  mounted() {
    //对carTypes数据赋值
    this.getTreeData();
  }
};
</script>